#include "stdafx.h"
#include "Utilities/utilities.h" // if you use STL, please include this line AFTER all other include
#include "Controller/Scene.h"
#include "Model.h"
#include "Vertex.h"
#include "Shader.h"


void Model::Init ()
{
	//GLuint nVertex, nIndex;
	//Vertex * vertexData = NULL; 
	//GLuint * indexData = NULL;

	////buffer object
	//InitFromArray(nVertex, nIndex, vertexData, indexData);

	//delete[] vertexData;
	//delete[] indexData;
}

void Model::InitFromArray(GLuint nVertex, GLuint nIndex, Vertex * vertexData, GLuint * indexData)
{
	//buffer object
	glGenBuffers(1, &m_vboId);
	glBindBuffer(GL_ARRAY_BUFFER, m_vboId);
	glBufferData(GL_ARRAY_BUFFER, sizeof(Vertex) * nVertex, vertexData, GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	
	glGenBuffers(1, &m_iboId);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iboId);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * nIndex, indexData, GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

	m_nIndices = nIndex;
}

void Model::Bind (Shader * shader)
{
	glBindBuffer(GL_ARRAY_BUFFER, m_vboId);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_iboId);

	// Vertex's attributes
	if(shader->m_positionAttribute != -1)
	{
		glEnableVertexAttribArray(shader->m_positionAttribute);
		glVertexAttribPointer(shader->m_positionAttribute, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
	}
	if(shader->m_normAttribute != -1)
	{
		glEnableVertexAttribArray(shader->m_normAttribute);
		glVertexAttribPointer(shader->m_normAttribute, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) sizeof(Vector3));
	}
	if(shader->m_uvAttribute != -1)
	{
		glEnableVertexAttribArray(shader->m_uvAttribute);
		glVertexAttribPointer(shader->m_uvAttribute, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*) (sizeof(Vector3) * 2));
	}
}

void Model::UnBind ()
{
	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
}

void Model::CleanUp ()
{
	glDeleteBuffers(1, &m_vboId);
	glDeleteBuffers(1, &m_iboId);
}